import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {Message} from "element-ui";

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  console.log("beforeEach");
  // start progress bar
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  if (to.path === '/sign-up') {
    next()
  } else {
    const hasToken = getToken()
    if (hasToken) {
      if (to.path === '/login') {
        next({path: '/'})
        NProgress.done()
      } else {
        next()
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login`)
        Message({
          message: '尚未登录',
          type: 'error',
          center: true,
          duration: 2 * 1000
        })
        next(`/login`)
        NProgress.done()
      }
    }
  }

})

router.afterEach(() => {
  NProgress.done()
})
